package gam.t1;

import gam.t1.conf.TextConfig;
import me.clip.placeholderapi.PlaceholderAPI;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

public class JoinMsg extends JavaPlugin implements Listener, CommandExecutor {
    private boolean placeholder = false;
    @Override
    public void onEnable() {
        try {
            Class.forName("io.papermc.paper.threadedregions.RegionizedServerInitEvent");
        } catch (ClassNotFoundException e) {
            getLogger().warning("This plugin is only support with Folia Server.");
            getServer().getPluginManager().disablePlugin(this);
            return;
        }
        if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") == null){
            getLogger().warning("Unknown the Plugin: PlaceholderAPI");
        } else placeholder = true;
        try {
            TextConfig.load(this);
        } catch (IOException e) {
            e.printStackTrace();
        }
        getServer().getPluginManager().registerEvents(this,this);
        getServer().getPluginCommand("joinmsg").setExecutor(this);
    }
    @EventHandler(priority = EventPriority.HIGHEST)
    public void join(PlayerJoinEvent e) throws Exception {
        for (String text : TextConfig.TEXTS) {
            if (placeholder) text = PlaceholderAPI.setPlaceholders(e.getPlayer(), text);
            Component parser = TextParser.parser(text);
            e.getPlayer().sendMessage(parser);
        }
    }

    @Override
    public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
        if (command.getName().equals("joinmsg")){
            if (args.length >= 1){
                if (args[0].equals("reload")){
                    try {
                        TextConfig.load(this);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    sender.sendMessage("Plugin : JoinMsg Reload Success!");
                }
            }
        }
        return false;
    }

    @Override
    public @Nullable List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) {
        return Collections.singletonList("reload");
    }
}
